<?php
session_start();
//当前用户
$user = isset($_SESSION["user"])?$_SESSION["user"]:null;
$userId = $user?$user["id"]:null;

 /*$theme = isset($_GET["theme"])?$_GET["theme"]:null;
 if(!$theme){
    $theme = isset($_COOKIE["theme"])?$_COOKIE["theme"]:null; }else{
             setcookie("theme",$theme);
 }
if(!$theme) $theme = "default";*/

//数据库
function createDb(){
return new mysqli("localhost","root","root","mydb");
}

function pageURL($pageIndex){
    $pageString = "pageIndex=$pageIndex";
    foreach ($_GET as $k => $v) {
        if($k==="pageIndex") continue;
        $pageString .="&$k=$v";
    }
    return $pageString;
}
function getParam($name){
    $value = isset($_GET[$name])?$_GET[$name]:null;
    $value = str_replace("'","''",$value);
    return $value;
}

//分页
function pageable($tbname,$where,$order,$pageIndex,$pageSize){
    $start = ($pageIndex-1)*$pageSize;
    $conn = createDb();
    $itemsSql = "SELECT * FROM `$tbname`";
    if($where) $itemsSql.= " where ".$where;
    if($order) $itemsSql.=" ORDER BY ".$order;
    $itemsSql.=" limit $start,$pageSize";
    //var_dump($itemsSql);
    $rs = $conn->query($itemsSql);
    $items =[];
    while($record = $rs->fetch_assoc()) $items[]=$record;
    $rs->close();

    $countSql = "select count(*) as c from `$tbname`";
    if($where) $countSql .=" where ".$where;
    $rs = $conn->query($countSql);
    $total = $rs->fetch_assoc()["c"];
    $rs->close();
    $pageCount = ceil($total/$pageSize);

    return [
        "items"=>$items,
        "total"=>$total,
        "pageCount" =>$pageCount
    ];
}